package com.example.ai.service;

import cn.hutool.core.util.StrUtil;
import com.example.ai.entity.ChatMessage;
import com.example.ai.entity.ChatSession;
import com.example.ai.mapper.ChatHistoryMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ChatHistoryService {

    @Autowired
    private ChatHistoryMapper historyMapper;

    /**
     * 创建新对话
     *
     * @param userId
     * @return
     */
    public String createSession(String userId) {
        String sessionId = generateSessionId();
        ChatSession session = new ChatSession(
                sessionId, userId, "新对话", null, null
        );
        historyMapper.createSession(session);
        return sessionId;
    }

    // 保存消息对（用户提问 + AI回答）
    @Transactional
    public void saveMessagePair(String userId,
                                String sessionId,
                                String userMessage,
                                String aiResponse,
                                int usedTokens) {

        //判断是否有sessionId
        if (StrUtil.isBlank(sessionId)) {
            sessionId = generateSessionId();
            ChatSession session = new ChatSession(
                    sessionId, userId, userMessage, null, null
            );
            historyMapper.createSession(session);
        }
        // 保存用户消息
        historyMapper.insertMessage(new ChatMessage(
                null, sessionId, "user", userMessage, null, null
        ));

        // 保存AI回复
        historyMapper.insertMessage(new ChatMessage(
                null, sessionId, "assistant", aiResponse, usedTokens, null
        ));

        // 更新会话时间
        updateSessionTime(sessionId);
    }

    /**
     * 查询最近5条对话
     *
     * @param sessionId
     * @return
     */
    public List<ChatMessage> getRecentHistory(String sessionId) {
        return historyMapper.selectMessages(sessionId).stream()
                .sorted((m1, m2) -> m2.getCreateTime().compareTo(m1.getCreateTime()))
                .limit(5)
                .collect(Collectors.toList());
    }

    /**
     * 查询用户session
     *
     * @param userId
     * @return
     */
    public List<ChatSession> selectSessions(String userId) {
        return historyMapper.selectSessions(userId, 0, 10);
    }

    private String generateSessionId() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    private void updateSessionTime(String sessionId) {

        historyMapper.updateSessionTime(sessionId);
    }
}
